const fs = require("fs");
const { resolvepath, logger } = require("../setting/setting.js");

let myfs = {
  isexists: async function (path) {
    //判断目录是否存在
    try {
      let isexists = await fs.existsSync(path);
      return isexists;
    } catch (error) {
      throw error;
    }
  },

  isfolder: async function (path) {
    let isexists = await this.isexists(path);
    //判断是否为文件夹
    if (isexists) {
      try {
        let result = fs.statSync(path);
        return result.isDirectory();
      } catch (error) {
        logger.publicerror("fs", error);
        throw "isfolder is error";
      }
    } else {
      logger.publicerror("fs", `不存在目标文件夹:${path}`);
      throw "不存在目标文件夹";
    }
  },

  readdir: async function (path) {
    let fullpath = resolvepath.root_path + path;
    let result = await this.isfolder(fullpath);
    //读取文件夹下所有文件名
    if (result) {
      try {
        let data = fs.readdirSync(fullpath);
        return data;
      } catch (error) {
        logger.publicerror("fs", error.message);
        throw error;
      }
    } else {
      logger.publicerror("fs", `目标不是文件夹:${path}`);
      throw "目标不是文件夹";
    }
  },

  readflie: async function (path) {
    let fullpath = resolvepath.root_path + path;
    let result = await this.isfolder(fullpath);
    //读取文件的内容
    if (!result) {
      try {
        let data = fs.readFileSync(fullpath);
        return data.toString();
      } catch (error) {
        logger.publicerror("fs", error.message);
        throw error;
      }
    } else {
      logger.publicerror("fs", `目标不是文件:${path}`);
      throw "目标不是文件";
    }
  },
};

module.exports = {
  myfs,
};
